import { useRoute } from 'vue-router'
import { useModulePageStore } from '@/store'
import { getPageSettingDetail, savePageSetting } from '@/api/module-page'
import modulePageTemplates from '@/components/edit/template-data/module-page-data'
import { ElMessage } from 'element-plus'

export default function useModulePageFun() {
    const route = useRoute()
    const modulePageStore = useModulePageStore()

    // 获取app数据
    const getAppData = () => {
        const { type, id } = route.params
        return new Promise(async (resolve, reject) => {
            const res = await getPageSettingDetail({
                type,
                id
            })
            if (res.code === 200) {
                const data = res.data
                const modulePages = data['module_pages'] || []
                const extendJson = JSON.parse(data['extend_json'] || '{}')
                
                Object.assign(modulePageStore.modulePageData, {
                    name: data.name,
                    code: data.code,
                    pages: modulePages
                })
                modulePages.forEach(item => {
                    if (item.type === 3) {
                        const templateData = Object.values(modulePageTemplates).find(n => n.router === item.code) || {}
                        extendJson[item.code] = Object.assign(templateData, (extendJson[item.code] || {}))
                    }
                })
                modulePageStore.modulePageConfigs = extendJson
                modulePageStore.pageId = modulePageStore.modulePageData?.pages?.find(item => item.type === 3)?.code || ''
                resolve(res)
            } else {
                reject(res)
            }
        })
    }
    
    // 保存数据
    const saveAppData = () => {
        const { type, id } = route.params
        return new Promise(async (resolve, reject) => {
            const res = await savePageSetting({
                type,
                id,
                extend_json: JSON.stringify(modulePageStore.modulePageConfigs)
            })
            if (res.code === 200) {
                ElMessage({
                    message: '保存成功',
                    grouping: true,
                    type: 'success'
                })
                resolve(res)
            } else {
                ElMessage({
                    message: '保存失败',
                    grouping: true,
                    type: 'error'
                })
                reject(res)
            }
        })
    }

    return {
        getAppData,
        saveAppData
    }
}